package controllers

import (
	"github.com/astaxie/beego"
	"fmt"
	"encoding/json"
)

type ParamController struct {
	beego.Controller
}

type user struct {
	Name string `form:"username"`
	Age  int    `form:"age"`
}

/**
	获取参数
 */
func (this *ParamController) TestParam() {
	name := this.GetString("name")
	age, error := this.GetInt("age")
	if error != nil {
		fmt.Println(error.Error())
		panic(error)
	}
	fmt.Printf("the name is %s,the age is %d\n", name, age)
	this.Ctx.WriteString("read param success")
}

/**
	获取表单参数，并把表单参数转换为struct对象
 */
func (this *ParamController) ParseParamToStruct() {
	u := user{}
	if error := this.ParseForm(&u); error != nil {
		fmt.Println(error.Error())
		panic(error)
	}
	fmt.Printf("the name is %s,the age is %d\n", u.Name, u.Age)
	this.Ctx.WriteString("parse param success")
}

/**
	获取表单参数，并把表单参数转换为struct对象
 */
func (this *ParamController) ReadRequestBody() {
	requestBody := this.Ctx.Input.RequestBody
	user := user{}
	if error := json.Unmarshal(requestBody, &user); error != nil {
		fmt.Println(error)
		panic(error)
	}

	fmt.Printf("the name is %s,the age is %d\n", user.Name, user.Age)
	this.Ctx.WriteString("read request body success")
}

func (this *ParamController) GetUploadFile() {
	f, header, error := this.GetFile("test")
	if error != nil {
		fmt.Println(error.Error())
		panic(error)
	}
	defer f.Close()
	this.SaveToFile("test", "d:/"+header.Filename)
	this.Ctx.WriteString("upload file  success")
}
